﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace ClientApp
{
    public partial class EmployerForm : Form
    {
        private ClientApp _parent;

        public EmployerForm(ClientApp parent)
        {
            _parent = parent;

            InitializeComponent();
        }

        private void EmployerForm_Load(object sender, EventArgs e)
        {
            List<Activity> activities = DatabaseAccess.Instance.Activities();
            foreach (Activity activity in activities)
            {
                ActivityComboBox.Items.Add(activity.Title);
            }

            FindCandidateDataGridView.Columns.Add("Id", "id");
            FindCandidateDataGridView.Columns["Id"].Visible = false;
            FindCandidateDataGridView.Columns.Add("FirstName", "Фамилия");
            FindCandidateDataGridView.Columns.Add("LastName", "Имя");
            FindCandidateDataGridView.Columns.Add("MiddleName", "Отчество");
            FindCandidateDataGridView.Columns.Add("Activity", "Профессия");
            FindCandidateDataGridView.Columns.Add("Salary", "Ожидаемый оклад");

            List<Skill> skills = DatabaseAccess.Instance.Skills();

            foreach (Skill skill in skills)
            {
                SkillsCheckListBox.Items.Add(skill.Title);
                SkillsCheckedListBox.Items.Add(skill.Title);
            }
        }

        private void ResetFilterButton_Click(object sender, EventArgs e)
        {
            SearchLocationTextBox.ResetText();

            for (int i = 0; i < SkillsCheckedListBox.Items.Count; i++)
            {
                SkillsCheckedListBox.SetItemChecked(i, false);
            }
        }

        private Point AddressToCoordinates(string address)
        {
            int ord = address.Aggregate(0, (current, t) => current + t);
            return new Point(address.Length % 10, ord % 10);
        }

        private void FindCandidatesButton_Click(object sender, EventArgs e)
        {
            if (SearchLocationTextBox.Text == "")
            {
                MessageBox.Show("Заполните поле адреса.", "Ошибка");
                return;
            }

            FindCandidateDataGridView.Rows.Clear();

            List<Skill> skills = (from object item in SkillsCheckedListBox.CheckedItems select DatabaseAccess.Instance.SkillByTitle(item as string)).ToList();

            List<Candidate> query_result = DatabaseAccess.Instance.Candidates(skills,
                                                                              AddressToCoordinates(AddressTextBox.Text),
                                                                              (int)DistanceNumericUpDown.Value);
            
            foreach (Candidate res_item in query_result)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.AddRange(new DataGridViewCell[6] { new DataGridViewTextBoxCell(),
                                                             new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell(), 
                                                             new DataGridViewTextBoxCell() });
                row.Cells[0].Value = res_item.Id;
                row.Cells[1].Value = res_item.LastName;
                row.Cells[2].Value = res_item.FirstName;
                row.Cells[3].Value = res_item.MiddleName;
                row.Cells[4].Value = res_item.Activity.Title;
                row.Cells[5].Value = res_item.SalaryExpected;

                FindCandidateDataGridView.Rows.Add(row);
            }

            FindCandidateResultGroupBox.Text = "Найдено: " + FindCandidateDataGridView.Rows.Count.ToString();
            ContactCandidateButton.Enabled = FindCandidateDataGridView.Rows.Count > 0;
        }

        private void EmployerForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            _parent.EmployerFormOpened = false;
        }

        private void ContactCandidateButton_Click(object sender, EventArgs e)
        {
            if (!DatabaseAccess.Instance.EmployerExists(LoginTextBoxForSearch.Text))
            {
                MessageBox.Show("Логин не существует в системе. Проверьте правильность ввода или зарегистрируйтесь.",
                                "Error");
                return;
            }

            _parent.EmployerRequests.Add("Работодатель \"" + LoginTextBoxForSearch.Text +
                "\" заинтересован в соискателе " + 
                DatabaseAccess.Instance.CandidateByID((uint)FindCandidateDataGridView.SelectedRows[0].Cells["Id"].Value).Login);

            MessageBox.Show("Заявка отправлена.");
        }

        private void OpenVacancyButton_Click(object sender, EventArgs e)
        {
            if (TitleTextBox.Text == "" ||
                ActivityComboBox.SelectedIndex < 0 ||
                AddressTextBox.Text == "" ||
                SalaryMaskedTextBox.Text == "")
            {
                MessageBox.Show("Заполните все текстовые поля формы.", "Ошибка");
                return;
            }

            if (!DatabaseAccess.Instance.EmployerExists(LoginTextBoxForNewVacancy.Text))
            {
                MessageBox.Show("Логин отсутствует в системе. Проверьте правильность ввода или зарегистрируйтесь.",
                                "Error");
                return;
            }

            SortedSet<uint> skills = new SortedSet<uint>();

            foreach (object item in SkillsCheckListBox.CheckedItems)
            {
                skills.Add(DatabaseAccess.Instance.SkillByTitle(item as string).Id);
            }

            DatabaseAccess.Instance.Add(new Vacancy(TitleTextBox.Text,
                                                    DatabaseAccess.Instance.EmployerByLogin(LoginTextBoxForNewVacancy.Text),
                                                    DatabaseAccess.Instance.ActivityByTitle(ActivityComboBox.Text),
                                                    AddressTextBox.Text,
                                                    Convert.ToUInt32(SalaryMaskedTextBox.Text),
                                                    skills));

            MessageBox.Show("Вакансия открыта.");
        }
    }
}
